package org.gdpu.service.impl;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.gdpu.base.DaoSupport;
import org.gdpu.model.Resource;
import org.gdpu.model.ResourceCategory;
import org.gdpu.model.Valid;
import org.gdpu.service.ResourceService;
import org.gdpu.util.ChangeTime;
import org.gdpu.util.fileConverter.FileConverter;
import org.gdpu.util.fileConverter.FileUtils;
import org.gdpu.vo.ResourceVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-6-4
 * Time: 下午1:21
 * To change this template use File | Settings | File Templates.
 */
@Service
@Transactional
public class ResourceServiceImpl extends DaoSupport<Resource> implements ResourceService {
    private static String SAVE_PATH_DIR = "D:/CRM/_file/";
    /**
     * 转换的pdf存放路径
     */
    private static String PDF_PATH_DIR = "D:/CRM/_file/_pdf/";

    public static String SWF_PATH_DIR = "_swf/";

    public static String ACCEPT_SUFIXS = "txt,doc,docx,ppt,pptx,pdf,xls,xlsx";

    private Logger logger = LogManager.getLogger(ResourceServiceImpl.class);
    private ResourceService resourceService;

    @Override
    public List<Resource> findResourceByUploader(String uploader) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("uploader", uploader);
//        params.put("valid", Valid.PASS_VALID);
        List<Resource> resources = (List<Resource>) this.findByFields(Resource.class, params);
        return resources.size() > 0 ? resources : null;
    }

    @Override
    public List<Resource> findResourceByCategory(String category) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("name", category);
        ResourceCategory resourceCategory = (ResourceCategory) this.findSpecialObject(ResourceCategory.class, params);
        if (resourceCategory == null) return null;
        //Map<String, Object> param = new HashMap<String, Object>();
        params.clear();
        params.put("resourceCategory.id", resourceCategory.getId());
        params.put("valid", Valid.PASS_VALID);
        List<Resource> resources = (List<Resource>) this.findByFields(Resource.class, params);
        return resources.size() > 0 ? resources : null;
    }

    @Override
    public List<Resource> findResourceByFileName(String information) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("fileName", information);
        params.put("introduction", information);
        List<Resource> resources = (List<Resource>) this.findByFuzzy(Resource.class, params);
        List<Resource> rs = new ArrayList<Resource>();
        if (resources != null) {
            for (Resource r : resources) {
                if (r.getValid() == Valid.PASS_VALID) rs.add(r);
            }
        }
        return rs.size() > 0 ? rs : null;
    }

    @Override
    public void judgeResource(Valid judge, int resourceId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("resourceId", resourceId);
        Resource resource = (Resource) this.findSpecialObject(Resource.class, params);
        resource.setValid(judge);
        this.update(resource);
    }

    @Override
    public boolean uploadResource(ResourceVO resourceVO) throws Exception {
        // 得到保存上传文件的目录的真实路径
        File dir = new File(SAVE_PATH_DIR);
        // 如果该目录不存在，就创建
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String name = ChangeTime.formatDate() + resourceVO.getFileName();
        FileInputStream is = new FileInputStream(resourceVO.getUpload());
        FileOutputStream os = new FileOutputStream(new File(dir, name));
        byte[] buf = new byte[1024];
        int len = -1;
        while ((len = is.read(buf)) != -1) {
            os.write(buf, 0, len);
        }

        is.close();
        os.close();

        //保存资源到数据库内
        Resource resource = new Resource();
        resource.setUploadTime(new Date());
        resource.setFileName(resourceVO.getFileName());
        resource.setFilePath(SAVE_PATH_DIR + name);
        resource.setIntroduction(resourceVO.getIntroduction());
        resource.setUploader(resourceVO.getUploader());
        resource.setDownloadTime(0);
        //找到资源分类
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("name", resourceVO.getResourceCategory());
        ResourceCategory category = (ResourceCategory) this.findSpecialObject(ResourceCategory.class, params);
        resource.setResourceCategory(category);
        try {
            convertFile(name, resourceVO.getPath());
            resourceService.save(resource);
            logger.trace("User:" + resourceVO.getUploader() + "upload a file:" + name);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
            return false;
        }
    }

    //显示某个资源
    private void convertFile(String name, String readPath) throws Exception {
        //文件后缀
        String sufix = FileUtils.getFileSufix(name);
        if (FileUtils.isSufix(sufix, ACCEPT_SUFIXS)) {
            //文件上传后路径
            String path = SAVE_PATH_DIR + name;
            FileConverter converter = new FileConverter();
            //swf文件路径
            String swf = readPath + SWF_PATH_DIR + FileUtils.getFilePrefix(name) + ".swf";
            //转换pdf文件临时路径
            String pdf = PDF_PATH_DIR + FileUtils.getFilePrefix(name) + ".pdf";
            converter.convert(path, pdf, swf);
//            FileUtils.deleteDirectory(PDF_PATH_DIR);
        }
    }

    @Override
    public List<Resource> allResource() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("valid", Valid.PASS_VALID);
        List<Resource> resources = (List<Resource>) this.findByFields(Resource.class, params);
        return resources != null ? resources : null;
    }

    @Override
    public boolean updateDownloadTime(int resourceId) {
        Resource resource = resourceService.find(Resource.class, resourceId);
        if (resource == null)
            return false;
        resource.setDownloadTime(resource.getDownloadTime() + 1);
        try {
            resourceService.update(resource);
        } catch (Exception e) {
            logger.trace(e);
            return false;
        }
        return true;
    }

    @Override
    public List<Resource> findByNotValid() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("valid", Valid.WAIT_VALID);
        List<Resource> resources = (List<Resource>) this.findByFields(Resource.class, params);
        return resources.size() > 0 ? resources : null;
    }

    @javax.annotation.Resource(name = "resourceServiceImpl")
    public void setResourceService(ResourceService resourceService) {
        this.resourceService = resourceService;
    }
}
